package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.mallcai.bigdata.ladon.datasource.RunInfoResult;
import com.mallcai.bigdata.ladon.dpl.entity.report.Report;
import com.mallcai.bigdata.ladon.dpl.entity.report.ReportSql;
import com.mallcai.bigdata.ladon.dpl.entity.report.SqlRunLog;
import com.mallcai.bigdata.ladon.service.report.ISqlRunLogQueueService;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import static com.mallcai.bigdata.ladon.service.report.impl.ReportQueryConstants.KEY_IS_CACHE_RESULT;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-20 13:06
 */
@Slf4j
@Service
@Order(2000)
public class LogSqlRunInfoPostHandler extends AbstractReportQueryPostHandler {

    @Autowired
    private ISqlRunLogQueueService logQueueService;

    @Override
    protected void postInternal(ReportQueryContext context) {
        ReportSql reportSql = context.getReportSql();
        Report report = context.getReport();
        RunInfoResult result = context.getResult();
        SqlRunLog sqlRunLog = new SqlRunLog();
        sqlRunLog.setCreatedBy(context.getUserId());
        sqlRunLog.setDsId(reportSql.getDsId());
        sqlRunLog.setSqlId(reportSql.getId());
        sqlRunLog.setReportId(report.getId());
        sqlRunLog.setErrInfo(result.getErrorInfo());
        sqlRunLog.setElapsedTime(result.getTimeElapsed());
        sqlRunLog.setComplete(result.isSuccess() ? 1 : 0);
        if (reportSql.getNeedDetailLog() == 1) {
            sqlRunLog.setText(result.getSql());
        }

        Boolean isCacheResult = context.getInnerParam(KEY_IS_CACHE_RESULT);
        if (isCacheResult != null && isCacheResult.booleanValue()){
            sqlRunLog.setCached(1);
        } else {
            sqlRunLog.setCached(0);
        }
        logQueueService.putLog(sqlRunLog);
    }

}
